/* 
 * 默认layout的js定义
 * @since 1.0 2014-6-27 by sutroon
 */

/**
 * 内容页面初始化
 * @since 1.0 2014-6-27 by sutroon
 */
function soui_init3(options) {
    var opts = $.extend({}, {'table': true, 'iframe': false, 'input': true, 'button': true, 'select': true}, options);
    $.ajaxSetup({
        cache: false //关闭AJAX相应的缓存
    });

    // 导航菜单下拉设置
    $('ul.sf-menu').superfish();

    // 提示设置
    $(document).tooltip({content: function () {
            var title = $(this).attr("title") || "";
            return $("<a>").html(title).html();
        }});

    if (opts.iframe) {
        // 设置iframe高度 2014-8-13 by sutroon
        setIframeHeight();
    }

    if (opts.input) {
        // 设置输入框
        config_input();
        // 全局设置输入框样式,在class加入spe则忽略 2015-3-25 SoChishun Added.
        $(':text:not(.spe), :password:not(.spe)').addClass('textbox');
        // html5图片上传预览功能 2015-3-27 SoChishun Added.
        html5_file_preview();
    }

    if (opts.table) {
        // 设置表格控件
        config_table();
    }

    if (opts.button) {
        // 设置按钮
        config_button();
    }

    if (opts.select) {
        // 设置下拉框 2014-9-28 by sutroon
        config_select();
    }

    // 设置fieldset
    config_fieldset();

    // 设置内容区域高度 2014-7-26 by sutroon
    $('#tabs .ui-tabs-panel').height($('.ui-layout-center').height() - 29 - 36).css('overflow', 'scroll');
}

// =================================== 方法分离 2014-9-27 by sutroon ======================================
/**
 * 配置按钮
 * @since 1.0 2014-7-26 by sutroon
 * @see http://api.jqueryui.com/theming/icons/
 */
function config_button() {
    $('.button, input[type=button], input[type=submit], input[type=reset], button[type=submit], button[type=reset]').button();
    $('.button').button({icons: {primary: 'ui-icon-grip-dotted-horizontal'}});
    $('.btn-plus').button({icons: {primary: 'ui-icon-plusthick'}});
    $('.btn-minus').button({icons: {primary: 'ui-icon-minusthick'}});
    $('.btn-edit').button({icons: {primary: 'ui-icon-pencil'}});
    $('.btn-search').button({icons: {primary: 'ui-icon-search'}});
    $('.btn-refresh').button({icons: {primary: 'ui-icon-refresh'}});
    $('.btn-trash').button({icons: {primary: 'ui-icon-trash'}});
    $('.btn-save').button({icons: {primary: 'ui-icon-disk'}});
    $('.btn-close').button({icons: {primary: 'ui-icon-closethick'}});
    $('.btn-export').button({icons: {primary: 'ui-icon-arrowthickstop-1-s'}});
    $('.btn-import').button({icons: {primary: 'ui-icon-arrowthickstop-1-n'}});
    $('.btn-doc').button({icons: {primary: 'ui-icon-document'}});
    $('.btn-check').button({icons: {primary: 'ui-icon-check'}});
    $('.btn-download').button({icons: {primary: 'ui-icon-arrowthickstop-1-s'}});
    $('.btn-upload').button({icons: {primary: 'ui-icon-arrowthickstop-1-n'}});
    $('.btn-locked').button({icons: {primary: 'ui-icon-locked'}});
    $('.btn-unlock').button({icons: {primary: 'ui-icon-unlocked'}});
    $('.btn-person').button({icons: {primary: 'ui-icon-person'}});
    $('.btn-options').button({icons: {primary: 'ui-icon-gear'}});
    $('.btn-up').button({icons: {primary: 'ui-icon-arrowthick-1-n'}});
    $('.btn-down').button({icons: {primary: 'ui-icon-arrowthick-1-s'}});
    $('.btn-arrowstop').button({icons: {primary: 'ui-icon-arrowstop-1-w'}});
    $('li>input[type=submit], li>button').parent().css('margin-top', 15);
    // 2014-9-27 by sutroon 新增效果
    $('#history-bar a').click(function () {
        $(this).addClass('cur').siblings().removeClass('cur');
    })
    $('.button-closeabled a').css('padding-right', 10).append('<span class="ui-icon  ui-icon-close" style="right:3px;"></span>'); // 2014-9-27 by sutroon 新增关闭按钮功能
    // 关闭历史菜单事件 2014-9-27 by sutroon
    $('.button-closeabled a .ui-icon-close').click(function () {
        var id = $(this).parent().data('id');
        history_btn_close(id); // 在Index/index.html
        return false;
    })

    // 2014-10-29 by sutroon 从对话框中的按钮关闭对话框
    // example: <input type="button" value="关闭" class="btn-close-dialog" />
    $('.btn-close-dialog').click(function () {
        close_dialog();
    })
}

/**
 * 设置表格或单元格
 * @since 1.0 2014-9-27 by sutroon
 */
function config_table() {
    // 设置音频播放器
    $('.audio-player').audioPlayer();
    // 设置单元格百分比进度条
    $('.td-progressbar').tdProgressbar();

    // 表格行点击选中 2014-8-13 by sutroon
    // 2014-9-27 by sutroon 新增data-func方法委托,如<tr data-key="{$vo.id}" data-func="after_select({$vo.state})">
    $('.table-list tr').click(function () {
        // 2014-10-6 取消选中 $(this).addClass('actived').siblings().removeClass('actived');
        var func = $(this).data('func');
        if (func) {
            eval(func);
        }
    })

    /**
     * 全选和反选
     * @since 1.0 2014-7-21 by sutroon
     * @example
     *        <th><input type="checkbox" />任务名称</th>
     *        <td><input type="checkbox" name="chk[]" value="{$vo.id}" />{$vo.name}</td>
     */
    $('th input:checkbox').click(function () {
        $(this).parentsUntil('table').parent().find('td input:checkbox').prop('checked', $(this).prop('checked'));
    });
}

/**
 * 设置下拉选项框
 * @param selector 选择器,如.class, #id
 * @param overwrite 是否覆盖设置
 * @since 1.0 2014-9-28 by sutroon
 */
function config_select(selector, overwrite) {
    if (undefined == selector) {
        selector = '.selectmenu';
    }
    if (undefined == overwrite) {
        overwrite = false;
    }
    $(selector).each(function () {
        var $sel = $(this);
        if (this.tagName == 'SELECT' && !$sel.hasClass('orginal-dom')) {
            if (overwrite || (!overwrite && $sel.next().attr('role') !== 'combobox')) {
                $sel.selectmenu().removeClass('ui-state-default').next().removeClass('ui-state-default').css('width', $sel.width() + 16);
                $sel.click(function () {
                    $(this).removeClass('ui-corner-all');
                });
            } else {
                $sel.selectmenu('refresh')
            }
        }
    })
}

/**
 * 设置输入框
 * @since 1.0 2014-11-18 by sutroon
 */
function config_input() {
    // 设置日期选择器
    $(".datepicker").datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat: 'yy-mm-dd',
        showWeek: true
    });
    // 设置时间日期选择器 see:http://trentrichardson.com/examples/timepicker/
    if ('undefined' !== typeof ($.fn.datetimepicker)) {
        $('.datetimepicker').datetimepicker({
            currentText: '现在',
            closeText: '确定',
            timeText: '时间',
            hourText: '小时',
            minuteText: '分钟',
            showSecond: false,
            changeMonth: true,
            changeYear: true,
            altFormat: "yy-mm-dd",
            altTimeFormat: "h:m t",
            showWeek: true
        });
    }

    // 设置可视化编辑器,控件不能加属性 require
    // 需在页面中增加隐藏控件 <input type="hidden" id="hidval_upload_handler" value="{:U('UploadHandler/kindeupload')}" />
    if ("undefined" !== typeof KindEditor) {
        var url = $('#hidval_upload_handler').val();
        if (undefined == url) {
            alert('未设置上传处理页面!');
        } else {
            KindEditor.create('.editor', {
                uploadJson: url,
                allowFileManager: false,
                autoHeightMode: true,
                items: [
                    'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
                    'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist',
                    'insertunorderedlist', '|', 'emoticons', 'image', 'multiimage', 'link']
            });
        }
    }

    $('.timepicker').timepicker();

    // 设置上传控件 2014-8-4 by sutroon
    $('.uploader').setFileInput();

    // 设置树形控件 2014-10-28 by sutroon
    $('.ul-tree').ulTree();

    // 设置选项按钮组
    $('.radio-button-set').buttonset();

    // 编辑时锁定控件 2014-12-27 by sutroon
    $('.edit-lock').each(function () {
        var $this = $(this);
        if ($this.val()) {
            $this.prop('readonly', true).css('color', '#555555');
        }
    })
}

/**
 * 设置fieldset 表单中更多选项的折叠和展开效果
 * @since 1.0 2014-6-23 by sutroon created; 1.1 2014-11-18 by sutroon 去除tohide方式较难理解的方法，改用func方法
 */
function config_fieldset() {
    $('form fieldset.optional').find('li').hide();
    $('form .optional legend').click(function () {
        var $legend = $(this);
        var txt = $legend.html();
        var func = $legend.parent().data('func');
        if (txt[0] != '[') {
            txt = '[+]' + txt;
        }
        if (txt[1] == '+') {
            txt = '[-]' + txt.substring(3);
            $legend.parent().find('li').show();
        } else {
            txt = '[+]' + txt.substring(3);
            $legend.parent().find('li').hide();
        }
        $legend.html(txt);
        if (undefined !== func) {
            eval(func);
        }
        // 2014-9-24 刷新对话框中iframe父窗体尺寸
        if (window.parent && window.parent.resize_dialog) {
            window.parent.resize_dialog(window.name);
        }
    });

    // 伸缩功能 2014-12-17 by sutroon
    // 默认展开是 <legend>[-]基础信息</legend>
    $('.exfieldset legend').click(function () {
        var $this = $(this);
        var txt = $(this).text();
        if (txt[0] != '[') {
            $this.next().hide();
            $this.text('[+]' + txt);
            return;
        }
        if (txt[1] == '-') {
            $this.next().hide();
            $this.text('[+]' + txt.substring(3));
        } else {
            $this.next().show();
            $this.text('[-]' + txt.substring(3));
        }
        resize_dialog();
    })
}

/**
 * 切换显示ajax加载效果
 * @param {boolean} display 显示或隐藏
 * @param {boolean} maskpage 是否遮罩整个页面
 * @returns {undefined}
 * @since 1.0 2014-6-17 created; 1.1 2014-10-6 by sutroon 新增loc,maskflag位置参数; 1.2 2014-11-3 by sutroon 修正全局(包括iframe)只会在顶层窗口有一个loading效果; 1.3 2015-3-16 by sutroon 精简重构
 */
function toggle_ajax_loading(display, maskpage) {
    var $body = window.parent ? $('body', window.parent.document) : $('body', document);
    var loading = '';
    if (maskpage) {
        loading = "<div id='soajax-loading' style='position:absolute;left:0;width:100%;height:100%;top:0;background:#FFFFFF;opacity:0.8;filter:alpha(opacity=90);z-index:9999999;'>";
        loading += "<div style='border:2px solid #B7CDFC;cursor:pointer;position:relative;top:45%;margin:0 auto;width:200px;height:36px;line-height:36px;font-size:12px;background:#fff;text-align:center;'>";
    } else {
        loading = "<div id='soajax-loading' style='position:absolute;left:45%;width:200px;height:36px;top:45%;background:#FFFFFF;opacity:0.8;filter:alpha(opacity=90);z-index:9999999;'>";
        loading += "<div style='border:2px solid #B7CDFC;cursor:pointer;margin:0 auto;width:200px;height:36px;line-height:36px;font-size:12px;background:#fff;text-align:center;'>";
    }
    loading += "正在读取数据，请稍后...</div></div>";
    if (display) {
        $body.append(loading);
    } else {
        if (undefined != $body.find("#soajax-loading")) {
            $body.find("#msoajax-loading").remove();
        }
    }
}

/**
 * 设置页面有无数据的显示内容
 * @param boolean hasRecord
 * @since 1.0 2014-10-14 by sutroon
 * @example
 *  <p id="page-no-record" style="display:none">当前没有任何数据，请联系管理员添加!</p>
 <div id="page-has-record">有内容</div>
 set_page_alt_content('{$hasRecord}');
 */
function set_page_alt_content(hasRecord) {
    if (hasRecord == '1' || hasRecord == 'TRUE') {
        $('#page-no-record').hide();
        $('#page-has-record').show();
    } else {
        $('#page-no-record').show();
        $('#page-has-record').hide();
    }
}

/**
 * 加载select控件的options
 * @param {string} selector 选择器
 * @param {string} uri ajax数据源地址
 * @param {string} def_option 默认第一行显示的文本,如:请选择...
 * @param {string} value 默认值
 * @param {string} perpends 添加的额外options,如果加前缀+则追加到后面,默认追加到前面
 * @param {function} func ajax加载完成后执行的方法
 * @returns {void}
 * @since 1.0 2014-6-17 by sutroon
 *      1.1 2014-7-16 by sutroon 新增如果控件不存在则跳出方法的逻辑
 *      1.2 2014-8-22 by sutroon 新增对树形数据的支持
 * @example 
 *      ajax_load_options('select[name="tbRoleID"]', '?s=Role/get_options/jsonpReturn/?', '请选择角色');
 *      var strQueueOpts = ajax_load_options('', '?s=AcdNo/get_queue_json.html', '选择队列号码', '{$data.queue}', '&lt;option value=""&gt;新增项&lt;/option&gt;', afterQueue);
 */
function ajax_load_options(selector, uri, def_option, value, prepends, func) {
    if (!func && !$(selector)[0]) {
        return;
    }
    $.getJSON(uri, function (data) {
        if (selector) {
            $(selector).empty();
        }
        if (!data) {
            return;
        }
        var $data = (typeof (data) == "object") ? data : $.parseJSON(data);
        var str = '';
        str = generate_options($data);
        if (prepends) {
            if (prepends[0] == '+') {
                str += prepends;
            } else {
                str = prepends + str;
            }
        }
        if (def_option) { // 添加默认选项到第一行
            str = '<option value="">' + def_option + '</option>' + str;
        }
        if (selector) {
            $(selector).html(str);
        }
        if (value && selector) {
            if (value.length > 4 && value.substring(0, 4) == 'TXT:') {
                $(selector).find('option:contains("' + value.substring(4) + '")').prop('selected', true);
            } else {
                $(selector).find('option[value="' + value + '"]').prop('selected', true);
            }
            str = $(selector).html();
        }
        // 如果有定义函数则执行
        if (func) {
            func(str);
        }
    });
}

/**
 * 根据json数据生成option控件
 * 如果有children节点则自动生成树形数据
 * @param {JSON} $data
 * @param {int} n 节点深度
 * @param {string} char 节点名称前缀
 * @returns {String}
 * @since 1.0 2014-8-22 by sutroon
 * @example
 *      var $data = (typeof (data) == "object") ? data : $.parseJSON(data);
 var str = '';
 str=generate_options($data);
 */
function generate_options($data, n, char) {
    if (n == undefined) {
        n = 0;
    }
    if (char == undefined) {
        char = '..';
    }
    var pad = '';
    while (n > 0) {
        pad += char;
        n--;
    }
    var str = '';
    if ($data.length) {
        // 多行格式
        for (var i = 0; i < $data.length; i++) {
            if ($data[i].id) {
                // 用于[{"id":"1","name":"name1"}]格式                
                str += '<option value="' + $data[i].id + '">' + pad + ($data[i].name ? $data[i].name : $data[i].text) + '</option>';
            } else if ($data[i].item) {
                // 用于[{"item":"1"},{"item":"2"}]
                str += '<option value="' + $data[i].item + '">' + pad + $data[i].item + '</option>';
            } else {
                // 用于{"item1","item2"}格式
                str += '<option value="' + $data[i] + '">' + pad + $data[i] + '</option>';
            }
            if ($data[i].children) {
                str += generate_options($data[i].children, n + 1, char);
            }
        }
    }
    else {
        // 用于{"a":"a1","b":"b2"}单行格式
        for (var attr in $data) {
            str += '<option value="' + attr + '">' + $data[attr] + '</option>';
        }
    }
    return str;
}

/**
 * 获取json数据对象的键值
 * @param {json} jsonObject
 * @returns {array}
 * @since 1.0 2014-12-23 by sutroon
 */
function get_json_keys(jsonObject) {
    var keys = [];
    for (var p in jsonObject) {
        if (jsonObject.hasOwnProperty(p)) {
            keys.push(p);
        }
    }
    return keys;
}

/**
 * Eggs ^_^
 * @since 1.0 2014-9-27 by sutroon
 */
function setEggs() {
    var eggs_i = 0;
    $('.eggs').click(function () {
        eggs_i++;
        if (eggs_i >= 5) {
            location.href = '?s=Index/eggs';
        }
    })
}

/**
 * 时钟功能
 * @returns {void}
 * @since 1.0 2014-8-15 by sutroon
 */
function clock() {
    var date = new Date();
    var arrdate = [date.getMinutes(), date.getSeconds()];
    var text = (arrdate[0] < 10 ? '0' + arrdate[0] : arrdate[0]) + ':' + (arrdate[1] < 10 ? '0' + arrdate[1] : arrdate[1]);
    var h = date.getHours();
    var w = '';
    if (h < 5) {
        w = '凌晨了,注意身体,早点休息哦!';
    } else if (h >= 5 && h < 11) {
        w = '早上好,一日之计在于晨,加油哦^_^';
    } else if (h > 14 && h < 18) {
        w = '下午好,保持愉快心情努力工作哦~';
    } else if (h > 18 && h < 21) {
        w = '晚上好!';
    } else if (h >= 21 && h < 24) {
        w = '夜深了,还没休息啊!';
    }
    var week = ['日', '一', '二', '三', '四', '五', '六'];
    var title = (date.getMonth() + 1) + '月' + date.getDate() + '日 周' + week[date.getDay()] + ' ' + date.getHours() + ':' + arrdate[0] + '<br />' + w;
    $('#head-clock').attr('title', title).text(text);
}


/**
 * 返回本月的最大天数
 * @param {Integer} iMonth
 * @param {Integer} iYear
 * @returns {Integer}
 * @since 1.0 2015-3-19 by sutroon
 */
function daysInMonth2(iMonth, iYear) {
    return 32 - new Date(iYear, iMonth, 32).getDate();
}

/**
 * 返回本月的最大天数
 * @param {Date} date
 * @returns {Integer}
 * @since 1.0 2015-3-19 by sutroon
 */
function daysInMonth(date) {
    return 32 - new Date(date.getYear(), date.getMonth(), 32).getDate();
}

function dateToString(date) {
    var _todayDate = date.getDate();
    var _year = date.getYear();
    !document.addEventListener || (_year += 1900);
    var _month = date.getMonth() + 1;
    return _year + "-" + _month + "-" + _todayDate;
}

/**
 * 判断是否闰年
 * @param {Integer} year
 * @returns {Boolean}
 * @since 1.0 2015-3-19 by sutroon
 */
function isLeapYear(year) {
    if (!isNaN(parseInt(year))) {
        return false;
    }
    return ((year % 4 == 0 && year % 100 != 0) || (year % 100 == 0 && year % 400 == 0));
}


/**
 * 获取前天、昨天、今天、明天、后天的时间
 * @param {Integer} n
 * @returns {string}
 * @since 1.0 2015-3-19 by sutroon
 * @example 
 * var dayDateTester={'前天':-2,'昨天':-1,'今天':0,'明天':1,'后天':2,'大后天':3};
 * var str='';    
 * for (var p in dayDateTester) {
 *      str += p + '=' + dayDate(dayDateTester[p]) + '\n';
 * }
 * alert(str);
 */
function dayDate(n) {
    var dd = new Date();
    dd.setDate(dd.getDate() + n);
    return dateToString(dd);
}

/**
 * 字符串转换为日期对象
 * @param {String} strTime
 * @returns {null|Date} 成功则返回Date对象，否则返回null
 * @since 1.0 2015-3-19 by sutroon
 */
function strToDate(strTime) {
    var n = Date.parse(strTime.replace(/-/g, "/"));
    return isNaN(n) ? null : new Date(n);
}

/**
 * 获取本周，本月，本季，本年，上月，上周，上季，去年，上二周，上二月的时间段
 * @param {String} name 名称
 * @param {JSON} options 选项
 *      String:date 基础日期
 *      Integer:int 变动数量
 *      String:type 算法类型 NORMAL=普通日历算法,FRONT=从今天向前推演,如2015-03-18本周应该是03-16至03-22,如果是FRONT则为03-12值03-18
 * @returns {Array}
 * @since 1.0 2015-3-19 by sutroon
 * @example
 * var dateRangeTester = {'本周': 'week', '本月': 'month', '本季': 'quarter', '本年': 'year', '上周': 'pweek', '上月': 'pmonth', '上季': 'pquarter', '去年': 'pyear', '上二周': 'p2week', '上二月': 'p2month'};
 * var str = '';
 * for (var p in dateRangeTester) {
 *      str += p + '=' + dateRange(dateRangeTester[p]) + '\n';
 * }
 * alert(str);
 */
function dateRange(name, options) {
    var opts = {'date': null, 'inc': null, 'type': 'FRONT'};
    opts = $.extend({}, opts, options);
    var beginTime;
    var endTime;
    var now = null;
    if (opts.date) {
        now = strToDate(opts.date);
    }
    if (!now) {
        now = new Date();
    }
    var objnow = {'month': now.getMonth(), 'year': now.getFullYear(), 'day': now.getDate(), 'wday': now.getDay()};
    switch (name) {
        case "week": //本周
            switch (opts.type) {
                case 'FRONT':
                    now.setDate(now.getDate() - 6);
                    break;
                default:
                    var day = now.getDay();
                    now.setDate(now.getDate() - (day - 1));
                    break;
            }
            beginTime = dateToString(now);

            now.setDate(now.getDate() + 6);
            endTime = dateToString(now);
            break;
        case "month":  //本月
            now.setDate(1);
            beginTime = dateToString(now);

            var days = daysInMonth(now);
            now.setDate(days);
            endTime = dateToString(now);
            break;
        case "quarter":   //本季
            var m = now.getMonth() + 1;
            var q = parseInt((m + 2) / 3); //得到第几季
            m = q * 3 - 2;  //得到季的首月份

            now.setMonth(m - 1);
            now.setDate(1);
            beginTime = dateToString(now);

            now.setMonth(now.getMonth() + 3);
            now.setDate(0);
            endTime = dateToString(now);
            break;
        case "year":    //本年
            now.setMonth(0);
            now.setDate(1);
            beginTime = dateToString(now);

            now.setMonth(11);
            now.setDate(31);
            endTime = dateToString(now);
            break;
        case "pweek":    //上周
            var day = now.getDay();
            now.setDate(now.getDate() - (day - 1) - 7);
            beginTime = dateToString(now);

            now.setDate(now.getDate() + 6);
            endTime = dateToString(now);

            break;
        case "pmonth":    //上月
            now.setDate(1);
            now.setMonth(now.getMonth() - 1);
            beginTime = dateToString(now);

            var days = daysInMonth(now);
            now.setDate(days);
            endTime = dateToString(now);
            break;
        case "pquarter":    //上季
            var m = now.getMonth() + 1;
            var q = parseInt((m + 2) / 3); //得到第几季
            m = q * 3 - 2;  //得到季的首月份

            m = m - 3; //上季
            now.setMonth(m - 1);
            now.setDate(1);
            beginTime = dateToString(now);

            now.setMonth(now.getMonth() + 3);
            now.setDate(0);
            endTime = dateToString(now);
            break;
        case "pyear":    //去年
            now.setFullYear(now.getFullYear() - 1);
            now.setMonth(0);
            now.setDate(1);
            beginTime = dateToString(now);

            now.setMonth(11);
            now.setDate(31);
            endTime = dateToString(now);
            break;
        case "p2week":    //上二周
            var day = now.getDay();
            now.setDate(now.getDate() - (day - 1) - 7 * 2);
            beginTime = dateToString(now);

            now.setDate(now.getDate() + 6 + 7);
            endTime = dateToString(now);
            break;
        case "p2month":    //上二月
            now.setDate(1);
            now.setMonth(now.getMonth() - 1 * 2);
            beginTime = dateToString(now);

            now.setMonth(now.getMonth() + 2);
            now.setDate(0);
            endTime = dateToString(now);
            break;
        case "customize":    //自定义
            beginTime = "";
            endTime = "";
            break;
    }
    return [beginTime, endTime];
}
/**
 * html5文件预览功能
 * @since 1.0 <2015-3-27> SoChishun Added.
 */
function html5_file_preview() {
    $('[type=file]').change(function (e) {
        var file = e.target.files[0];
        var url = URL.createObjectURL(file);
        var $file = $(this);
        var $img = $file.next('img.preview');
        if ($img[0] && 'IMG' == $img[0].tagName) {
            $img.attr('src', url);
        } else {
            $file.after('<img class="preview" src="' + url + '" style="max-width: 60px;max-height:60px;" />')
        }
    })
}